<template>
  <DatePicker v-bind="getBindValues" :value="props.value" @blur="handleBlur" @input="handleChange" />
</template>

<script setup name="basic-date-range">
import { ref, computed, unref, useAttrs, watch, watchEffect } from 'vue'
import { DatePicker } from 'element-ui'
import dateFormat from '@/utils/date_format'
import { isNull, isArray } from 'lodash-es'

const props = defineProps({
  value: {
    type: [Array, String],
    default: () => []
  },
  // 禁用时间范围
  rangeValue: {
    type: Number,
    default: 365
  },
  // 是否是重置，如果是则清空日期的禁用选项
  isReset: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['input', 'enter'])
const attrs = useAttrs()

const minDate = ref(null)
const maxDate = ref(null)

const getBindValues = computed(() => ({
  type: 'daterange',
  startPlaceholder: '开始日期',
  endPlaceholder: '结束日期',
  valueFormat: 'yyyy-MM-dd',
  pickerOptions: {
    disabledDate(time) {
      const currentDate = time.getTime()
      if (unref(minDate)) {
        const minTime = getTime(unref(minDate))
        if (props.rangeValue) {
          const endDate = dateFormat.afterDate(minTime, props.rangeValue)
          return currentDate < minTime || currentDate > endDate
        }
        return currentDate < minTime
      }

      if (unref(maxDate)) {
        return currentDate > getTime(unref(maxDate))
      }

      return false
    },
    onPick({ minDate: minTime, maxDate: maxTime }) {
      minDate.value = minTime
      maxDate.value = maxTime
    }
  },
  ...attrs
}))

watch(
  () => props.value,
  (val) => {
    if (isNull(val)) {
      minDate.value = null
      maxDate.value = null
    }
    if (val && isArray(val) && val.length) {
      minDate.value = val[0] ?? null
      maxDate.value = val[1] ?? null
    }
  },
  { immediate: true }
)

watchEffect(() => {
  if (props.isReset) {
    minDate.value = null
  }
})

function handleBlur({ value }) {
  if (isNull(value)) {
    minDate.value = null
  }
}

function handleChange(e) {
  if (isNull(e)) {
    minDate.value = null
  }
  emit('input', e)
}

function getTime(date) {
  return new Date(date).getTime()
}
</script>

<style>
.el-date-editor .el-range__icon {
  line-height: 27px;
}
</style>
